package com.azt.data.action;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.azt.api.dto.CentralizeProviderReportDto;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.azt.api.model.AjaxJson;
import com.azt.api.model.Pagination;
import com.azt.api.pojo.ProjectAnalysis;
import com.azt.api.service.PaginationService;
import com.azt.api.service.ProjectAnalysisService;
import com.azt.data.permission.MenuPermission;
import com.azt.data.utils.CommonUtil;
import com.azt.data.utils.ExcelExportEntityUtil;
import com.azt.data.utils.FreemarkerUtils;
import com.azt.data.utils.Globals;
import com.azt.data.utils.RequestUtils;
import com.azt.provider.mapper.ProjectMapper;
import com.azt.provider.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.StrUtil;

import net.sf.json.JSONArray;

/**
 * Created by zouheyuan on 2017/5/2.
 */
@Controller
@RequestMapping("/project")
public class ProjectAction extends BaseAction {

	@Autowired
	private ProjectMapper projectMapper;

	@Autowired
	private PaginationService paginationService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ProjectAnalysisService projectAnalysisService;

	@MenuPermission
	@RequestMapping(value = "/overview")
	public String overview(ModelMap model) {
		int allEnquiry = projectMapper.getAllEnquiry();
		int allQuote = projectMapper.getAllQuote();
		int enquiryPurNums = projectMapper.getEnquiryPurNums();
		int quoteProNums = projectMapper.getQuoteProNums();
		int acceptQuoteNums = projectMapper.getAcceptQuoteNums();
		int enquiryingNums = projectMapper.getEnquiryingNums();

		model.addAttribute("allEnquiry", allEnquiry);
		model.addAttribute("allQuote", allQuote);
		model.addAttribute("enquiryPurNums", enquiryPurNums);
		model.addAttribute("quoteProNums", quoteProNums);
		model.addAttribute("acceptQuoteNums", acceptQuoteNums);
		model.addAttribute("enquiryingNums", enquiryingNums);

		return "project/overview";
	}

	@MenuPermission
	@RequestMapping(value = "/detail")
	public String detail(Integer type, ModelMap model , Integer so_eid) {
		if (type == null) {
			type = 1;
		}
		model.addAttribute("type", type);
		model.addAttribute("so_eid", so_eid);
		return "project/detail";
	}

	@ResponseBody
	@RequestMapping(value = "/detatilData")
	public JSONObject detailData(HttpServletRequest request, Integer pageNo, Integer type) {
		Map searchMap = RequestUtils.getSearchMap(request);
		JSONObject json = new JSONObject();
		List<Map<String, Object>> selectList = null;
		Page<Object> startPage = null;
		if (type == null) {
			type = 1;
		}
		switch (type) {
			case 1: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = projectMapper.getEnquiryList(searchMap);
				break;
			}
			case 2: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = projectMapper.getQuoteList(searchMap);
				break;
			}
			case 3: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = userMapper.selectEnquiryCompany(searchMap);
				break;
			}
			case 4: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = projectMapper.getQuoteCompany(searchMap);
				break;
			}
			case 5: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = projectMapper.getEnquiryPriceByMonth();
				break;
			}
			case 6: {
				startPage = PageHelper.startPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);
				selectList = projectMapper.selectEnquiryVisit(searchMap);
				break;
			}
		}
		Pagination paginationList = paginationService.getPaginationList(startPage, selectList);
		RequestUtils.MapToModelMap(searchMap, request);
		String jsonString = JSON.toJSONString(paginationList.getList(), CommonUtil.jsonfilter,
				SerializerFeature.WriteDateUseDateFormat);
		JSONArray fromObject = JSONArray.fromObject(jsonString);
		json.put("data", fromObject);
		json.put("draw", paginationList.getPageNo());
		json.put("total", paginationList.getTotalCount());
		json.put("recordsTotal", paginationList.getTotalCount());
		json.put("recordsFiltered", paginationList.getTotalCount());
		return json;
	}

	@ResponseBody
	@RequestMapping(value = "/detailDataExport")
	public void detailDataExport(HttpServletRequest request, Integer type) {
		Map searchMap = RequestUtils.getSearchMap(request);
		JSONObject json = new JSONObject();
		List<Map<String, Object>> selectList = null;
		Page<Object> startPage = null;
		if (type == null) {
			type = 1;
		}
		switch (type) {
		case 1: {
			selectList = projectMapper.getEnquiryList(searchMap);
			ExcelExportUtil.exportExcel(new ExportParams("询价列表数据", null, "询价列表", "安装通询价列表数据"),
					ExcelExportEntityUtil.enquiryList(), selectList, request, response);
			break;
		}
		case 2: {
			selectList = projectMapper.getQuoteList(searchMap);
			ExcelExportUtil.exportExcel(new ExportParams("报价列表数据", null, "报价列表", "安装通报价列表数据"),
					ExcelExportEntityUtil.quoteList(), selectList, request, response);
			break;
		}
		case 3: {
			selectList = userMapper.selectEnquiryCompany(searchMap);
			ExcelExportUtil.exportExcel(new ExportParams("询价排名", null, "询价排名", "安装通采购商询价数量排名"),
					ExcelExportEntityUtil.enquiryNumList(), selectList, request, response);
			break;
		}
		case 4: {
			selectList = projectMapper.getQuoteCompany(searchMap);
			ExcelExportUtil.exportExcel(new ExportParams("报价排名", null, "报价排名", "安装通供应商报价数量排名"),
					ExcelExportEntityUtil.quoteNumList(), selectList, request, response);
			break;
		}
		case 5: {
			selectList = projectMapper.getEnquiryPriceByMonth();
			ExcelExportUtil.exportExcel(new ExportParams("询价金额", null, "询价金额", "安装通供各月询价金额总量"),
					ExcelExportEntityUtil.enquiryPriceList(), selectList, request, response);
			break;
		}
		}

	}

	/**
	 * 获取每月询报价单数据
	 *
	 * @return
	 */
	@RequestMapping("/getProjectsData")
	@ResponseBody
	public AjaxJson getProjectsData() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> list = projectMapper.getProjectsByMonth(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	/**
	 * 获取每月采纳的报价数量
	 *
	 * @return
	 */
	@RequestMapping("/getAcceptQuote")
	@ResponseBody
	public AjaxJson getAcceptQuote() {
		String startDate = getPara("startDate");
		String endDate = getPara("endDate");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		if (StrUtil.isBlank(startDate)) {
			endDate = sdf.format(c.getTime());
			c.add(Calendar.MONTH, -11);
			startDate = sdf.format(c.getTime());
		}
		List<Map<String, Object>> list = projectMapper.getAcceptNums(startDate, endDate);
		AjaxJson json = AjaxJson.success();
		json.setObj(list);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		json.setAttributes(params);
		return json;
	}

	@RequestMapping("/getQuoteCompanyTop10")
	@ResponseBody
	public List<Map<String, Object>> getQuoteTopTen() {
		List<Map<String, Object>> list = projectMapper.getQuoteCompanyTop10();
		return list;
	}

	/**
	 * 各类报价占比
	 * 
	 * @return
	 */
	@RequestMapping("/getCategoryQuote")
	@ResponseBody
	public List<Map<String, Object>> getCategoryCompany() {
		List<Map<String, Object>> list = projectMapper.getQuoteNumByCategory();
		return list;

	}

	/**
	 * @Title: exponential
	 * @Description: 项目价格分析
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 * @return: String
	 * @author: 查恒 2017年6月7日 上午10:44:39
	 */
	// 价格指数
	@RequestMapping(value = "/priceExponential")
	public String exponential(HttpServletRequest request, HttpServletResponse response, Model model, String month)
			{
		 //服务器地址  
		//String ServerUrl="http://" + request.getServerName()+ ":" + request.getServerPort(); 
		//月份为空就选当月
		if(StringUtils.isBlank(month)){
			SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM");
			month = sdf.format(new Date());
		}
		// 查询当月的表数据存在否，不存在就生成
		ProjectAnalysis projectAnalysis = projectAnalysisService.getProjectAnalysisByMonth(month);
		if (projectAnalysis != null) {
			model.addAttribute("projectAnalysis", projectAnalysis);
		} else {
			// 生成价格数据表
			String currentPath = request.getSession().getServletContext().getRealPath("\\res\\images");
			Map<String, List<String>> listUrlMap = projectAnalysisService.getProjectPrice(currentPath,month);
			// 调用Html模板生成html代码路径保存到数据库
			String tempath = request.getSession().getServletContext().getRealPath("/WEB-INF/report/productPrice");
			try {
				String hostPath="http://" +request.getServerName() +":"+request.getServerPort(); 
				StringWriter writer = FreemarkerUtils.createHtmlWriter(tempath,listUrlMap,hostPath);
				if (writer != null && StringUtils.isNotBlank(writer.toString())) {
					// 存数据库
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
					Date generatetime = df.parse(month);
					ProjectAnalysis pas = new ProjectAnalysis();
					pas.setTemplate(writer.toString());
					pas.setGeneratetime(generatetime);
					pas.setCreatetime(new Date());
					projectAnalysisService.saveOrUpdate(pas);
					model.addAttribute("projectAnalysis", pas);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			 
		}
		
		model.addAttribute("month", month);
		
		return "productPrice/priceExponential";
	}
	
	//验证数据
	@ResponseBody
	@RequestMapping(value = "/checkdata")
	public AjaxJson checkdata(String month){
		if(StringUtils.isNotBlank(month)){
			ProjectAnalysis projectAnalysis = projectAnalysisService.getProjectAnalysisByMonth(month);
			if(projectAnalysis!=null){
				return AjaxJson.success();
			}else{
				return AjaxJson.error("没有数据。");
			}
		}else{
			return AjaxJson.error("没有选择月份。");
		}
		
	}
	

	//下载价格分析页面
	@RequestMapping(value = "/downloadPrice")
	public void downloadPrice(HttpServletRequest request, HttpServletResponse response,String month){
		if(StringUtils.isNotBlank(month)){
			ProjectAnalysis projectAnalysis = projectAnalysisService.getProjectAnalysisByMonth(month);
			if(projectAnalysis!=null){
				try {
				String title=month+".html";
				String template = projectAnalysis.getTemplate();
				response.setContentType("text/html;charset=utf-8"); 
				response.setHeader("Content-Disposition", "attachment;filename=" + CommonUtil.toUtf8String(request.getHeader("User-Agent") , "价格分析表_"+title));
				response.setCharacterEncoding("utf-8"); 
				Writer out = response.getWriter();
				 out.write(template);
				 out.flush();
				 out.close();
				//ServletOutputStream outputStream = response.getOutputStream();
				//outputStream.write(template.getBytes());
				//outputStream.flush();
				//outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
